/**
 * Created by ztt on 2017/11/17.
 */
const express = require('express');
const app = express();

/**
 * todo:跨域处理
 */
//解决跨域
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('X-JSON', '*');
    next();
});

//或者
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Methods', '*');
    res.header('X-JSON', '*');
    //设置仅接受 application/json 格式请求
    //res.header('Content-Type', 'application/json;charset=utf-8');
    next();
});

app.get('/path/to/getTime',function (req,res) {
    let t1=req.query.t;
    console.log(t1);
    const date = new Date();
    const t2=date.getTime();
    res.send((t1-t2)+':'+t2);
});
app.get('/sandbox/gettime',function (req,res) {
    const date = new Date();
    res.send(date.getTime()+"");
});
app.get('/sandbox/gettime2',function (req,res) {
    res.send(getDateStr()+'bb');
});

app.get('/path/to/getTime2',function (req,res) {
    const date = new Date();
    res.send(date.getTime()+"");
});
app.get('/api/time',function (req,res) {
    const date = new Date();
    res.send({data:{time:date.getTime()}});
});
function getDateStr(){
    const date = new Date();
    const month = date.getMonth()+1;
    const day = date.getDate();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();
    const dateStr = date.getFullYear()+'-'+(month>9?'':0)+month+'-'+(day>9?'':0)+day+' '+(hours>9?'':0)+hours+':'+(minutes>9?'':0)+minutes+':'+(seconds>9?'':0)+seconds;
    return dateStr;
}


const server = app.listen(3000, function () {
    const host = server.address().address
    const port = server.address().port
    console.log("应用实例，访问地址为 http://%s:%s", host, port)
});
